package com.atguigu.userprofile.util;

import com.atguigu.userprofile.constant.ConstCode;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Mysql工具类
 */
public class MySqlUtil {

    //private static final String URL  = "jdbc:mysql://hadoop102:3306/user_profile_manager0926?characterEncoding=utf-8&useSSL=false" ;
    //private static final String URL  = MyPropsUtil.get("mysql.url") ;
    private static final String URL  = MyPropsUtil.get(ConstCode.MYSQL_URL) ;
    private static final String USERNAME = MyPropsUtil.get(ConstCode.MYSQL_USERNAME) ;
    private static final String PASSWORD = MyPropsUtil.get(ConstCode.MYSQL_PASSWORD) ;


    /**
     * 通用查询方法 , 返回一个对象
     *
     * 1. querySql   : 查询要执行的Sql
     * 2. returnType : 返回值类型
     *
     */
    public static <T> T selectOne( String querySql , Class<T> returnType ,  Boolean isUnderScoreToCamel   ){
        List<T> selectList = selectList(querySql, returnType , isUnderScoreToCamel );
        if(!selectList.isEmpty()){
            T t = selectList.get(0);
            return t ;
        }
        return null ;
    }

    /**
     * 通用查询方法 , 返回对象列表
     *
     * 1. querySql   : 查询要执行的Sql
     * 2. returnType : 返回值类型
     *
     */
    public static  <T> List<T> selectList(String querySql , Class<T> returnType , Boolean isUnderScoreToCamel  ){
        List<T> selectList =  new ArrayList<>();
        Connection connection = null ;
        PreparedStatement preparedStatement = null ;
        ResultSet resultSet = null ;
        try {
            Class.forName("com.mysql.jdbc.Driver") ;
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            preparedStatement = connection.prepareStatement(querySql);
            resultSet = preparedStatement.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取到结果列的个数
            int columnCount = metaData.getColumnCount();
            //处理结果

            while(resultSet.next()){
                //一行数据封装成一个对象
                T returnObj = returnType.newInstance(); // 要求类中要提供无参数构造器
                for (int i = 1; i <= columnCount; i++) {
                    //结果列名
                    String columnLabel = metaData.getColumnLabel(i);
                    //获取列值
                    Object columnValue = resultSet.getObject(columnLabel);
                    //处理类的属性
                    // columnLabel => FieldName
                    String fieldName ;
                    if(isUnderScoreToCamel){
                        // 下划线 到 驼峰的处理
                        fieldName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnLabel);
                    }else{
                        fieldName = columnLabel ;
                    }
                    //通过反射的方式给对象的属性赋值
                    //Field fieldObj = returnType.getDeclaredField(fieldName);
                    //fieldObj.set(returnObj ,columnValue );
                    BeanUtils.copyProperty(returnObj , fieldName , columnValue );

                }

                //将处理好的对象添加到集合中
                selectList.add( returnObj ) ;
            }

            return selectList ;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询mysql失败: " + e.getMessage()) ;
        }finally {
            try {
                if(resultSet != null && !resultSet.isClosed()) {resultSet.close() ;}
                if(preparedStatement != null && !preparedStatement.isClosed()) {preparedStatement.close();}
                if(connection!= null && !connection.isClosed()){connection.close(); }

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
